from getpass import getpass
from base64 import b64encode as _base64encode
from hashlib import sha256
from dicttoxml import dicttoxml
# this is a setting file

#INIT_HOST="http://192.168.8.1/html/index.html"
INIT_HOST="http://192.168.8.1/html/unicomhome.html"
LOGIN_HOST="http://192.168.8.1/api/user/login"
DEAL_HOST="http://192.168.8.1/html/statistic.html"
STATICS_URL="http://192.168.8.1/api/monitoring/traffic-statistics"
MONTH_URL="http://192.168.8.1/api/monitoring/month_statistics"
# for most of mobile device this is a default user name
USER_NAME="admin"
import xmltodict
from math import log

def parseUeage(xml_obj):
    kind = {
        1:lambda x: ("use : %.2f %s " %(x / 1024.0 **1 , "KB")),
        2:lambda x: ("use : %.2f %s " %(x / 1024.0 **2 , "MB")),
        3:lambda x: ("use : %.2f %s " %(x / 1024.0 **3 , "GB")),
    }
    usage = dict(xmltodict.parse(xml_obj)["response"])
    useed = float(usage["CurrentMonthUpload"]) + float(usage["CurrentMonthDownload"])
    print(kind[int(log(useed,1024))](useed))
    

def base64encode(raw_str):
    return _base64encode(raw_str.encode()).decode()

def login(user):
    """
    this is a function supported login service.
    input user/passwd from stdin ,then output.
    """
    u = user
    if not u :
        u = input("intput user :")
    p = getpass("input passwd : (%s)"%u)
    return (u,p)


def SHA256(raw_str):
    return sha256(raw_str.encode()).hexdigest()
    
def login_encode_type4(token,user=USER_NAME):
    
    name,passwd =  login(user)
    psd = base64encode(SHA256(user + base64encode(SHA256(passwd)) + token))
    return  dicttoxml({
        "Username":name,
        "Password":psd,
        "password_type":4,
    },custom_root="request",attr_type=False).decode()
                      
    


